(function () {
  //获取元素
  let caroselList = document.querySelector("#carosel");
  let cnt = 0;
  let banner = document.querySelector("#banner");
  let lock = true;

  //复制第一张图片
  let pic1 = caroselList.children[0].cloneNode(true);
  caroselList.appendChild(pic1);

  //右移动
  function movingRigh() {
    caroselList.style.transition = "transform 0.5s ease 0s";
    cnt++;
    caroselList.style.transform = `translateX(${-25 * cnt}%)`;
    if (cnt > 2) {
      setTimeout(() => {
        caroselList.style.transition = "none";
        cnt = 0;
        caroselList.style.transform = `translateX(${-25 * cnt}%)`;
      }, 500);
    }
    setCircles();
  }

  //设置小圆点
  let circles = document.querySelector("#circles");
  function setCircles() {
    let lis = circles.getElementsByTagName("li");
    for (let i = 0; i < lis.length; i++) {
      lis[i].className = "";
    }
    lis[cnt % 3].className = "active";
  }

  circles.onclick = function (e) {
    if (!lock) return;
    lock = false;
    if (e.target.tagName.toLowerCase() === "li") {
      let num = e.target.getAttribute("data-n");
      let lis = circles.getElementsByTagName("li");
      for (let i = 0; i < lis.length; i++) {
        lis[i].className = "";
      }
      lis[num].className = "active";
      cnt = num;
      caroselList.style.transition = "transform 0.5s ease 0s";
      caroselList.style.transform = `translateX(${-25 * cnt}%)`;
    }
    setTimeout(() => {
      lock = true;
    }, 500);
  };

  //自动播放
  let timer = setInterval(() => {
    movingRigh();
  }, 2000);

  //鼠标悬停停止播放
  banner.addEventListener(
    "mouseover",
    () => {
      clearInterval(timer);
    },
    false
  );

  banner.addEventListener("mouseleave", () => {
    clearInterval(timer);
    timer = setInterval(() => {
      movingRigh();
    }, 2000);
  });
})();
